package com.party.web.web.controller.circle;


import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.core.model.circle.Circle;
import com.party.core.model.circle.CircleCode;
import com.party.core.model.circle.CircleTag;
import com.party.core.model.circle.WithTage;
import com.party.core.model.city.Area;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.XzgsAccountEnum;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.circle.ICircleService;
import com.party.core.service.circle.ICircleTagService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.system.IDictService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.circle.CircleBizNewService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.photo.AlbumBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.circle.CircleInput;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.security.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 圈子
 */
@Controller
@RequestMapping(value = "/circle")
public class CircleController {

    @Autowired
    private ICircleService circleService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private CircleBizService circleBizService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private ICircleTagService circleTagService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private CircleMemberBizService circleMemberBizService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private IPhotoProjectService photoProjectService;
    @Autowired
    private AlbumBizService albumBizService;
    @Autowired
    private CircleBizNewService circleBizNewService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 圈子列表页面
     */
    @RequestMapping(value = {"list", ""})
    public ModelAndView list(Page page, Circle circle, CommonInput commonInput) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("circle/circleList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        mv.addObject("input", commonInput);
        CurrentUser user = RealmUtils.getNewCurrentUser();

        List<MemberGroup> memberGroupList = new ArrayList<>();

        if (!Constant.MEMBER_XZGSADMIN.equals(user.getType())) {
            memberGroupList = memberGroupService.getChildWithMyAndName(user.getId());
            List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            params.put("orgIds", orgIds);
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(user.getId(), user.getPartnerId());
        }

        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("isChild", user.isChild());
        mv.addObject("isXzgsAdmin", user.isXzgsAdmin());

        circle.setDelFlag(Circle.DEL_FLAG_NORMAL);
        List<Map<String, Object>> list = circleService.webListPage(circle, params, page);

        for (Map<String, Object> item : list) {
            String id = (String) item.get("id");
            String mgrId = (String) item.get("mgrId");
            String filePath = fileBizService.getUploadCIPath(mgrId, "circle");
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + id);
            item.put("qrCodeUrl", qrCodeUrl);

            String fileContactPath = fileBizService.getUploadCIPath(mgrId, "circle/contact");
            String qrABCodeUrl = cosBizService.getPreviewPictureUrl(fileContactPath + id);
            item.put("qrABCodeUrl", qrABCodeUrl);
        }
        mv.addObject("list", list);
        mv.addObject("page", page);
        mv.addObject("circle", circle);
        return mv;
    }

    /**
     * 查看，增加，编辑圈子表单页面
     */
    @DataControl
    @RequestMapping(value = "form")
    public ModelAndView form(@ControlParam(table = "circle", column = "create_by", getMethodName = "getId", isRequired = false) Circle circle) {
        ModelAndView mv = new ModelAndView("circle/circleForm");
        if (StringUtils.isNotBlank(circle.getId())) {
            circle = circleService.get(circle.getId());

            CircleTag t = new CircleTag();
            t.setCircle(circle.getId());
            List<CircleTag> circleTags = circleTagService.list(t);
            mv.addObject("circleTags", circleTags);
        }
        if (StringUtils.isNotEmpty(circle.getArea())) {
            Area area = areaService.get(circle.getArea());
            mv.addObject("city", area.getId());
            mv.addObject("arParent", area.getParentId());
        }

        CurrentUser newCurrentUser = RealmUtils.getNewCurrentUser();
        List<MemberGroup> memberGroups = new ArrayList<>();
        if (!newCurrentUser.isChild()) {
            memberGroups = memberGroupService.getChildList(newCurrentUser.getId());
        } else if (newCurrentUser.isXzgsAdmin()) {
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(newCurrentUser.getId(), null);
        }
        mv.addObject("childrens", memberGroups);
        Dict dict = new Dict();
        dict.setType(DictEnum.CIRCLE_TYPE.getCode());
        mv.addObject("types", dictService.list(dict));
        mv.addObject("circle", circle);
        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);
        return mv;
    }

    /**
     * 保存圈子
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(CircleInput circleInput, BindingResult result, String childrenId) throws Exception {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            String memberId = RealmUtils.getNewCurrentUser().getId();
			if (StringUtils.isNotEmpty(childrenId)) {
				memberId = childrenId;
			} else if (Constant.MEMBER_XZGSADMIN.equals(RealmUtils.getCurrentUser().getType())) {
				memberId = RealmUtils.getNewCurrentUser().getPartnerId();
			}
            String circleId = circleInput.getId();
            circleInput.setMemo(circleInput.getMemo().trim());
            if (StringUtils.isNotEmpty(circleInput.getId())) {// 编辑表单保存
                Circle circleDb = circleService.get(circleInput.getId());
                MyBeanUtils.copyBeanNotNull2Bean(circleInput, circleDb);// 将编辑表单中的非\NULL值覆盖数据库记录中的值
                circleInput.setUpdateBy(memberId);

                memberId = circleDb.getCreateBy();

                if (circleInput.getCircleTags() != null) {
                    if (circleInput.getIsOpen().equals(CircleCode.CIRCLE_AUTH_TYPE_AUTH.getCode())) {
                        for (CircleTag circleTag : circleInput.getCircleTags()) {
                            if (circleTag.getTagName().equals("其他")) {
                                circleDb.setNoTypeIsOpen(circleTag.getIsOpen());
                            } else {
                                CircleTag t = circleTagService.get(circleTag.getId());
                                t.setIsOpen(circleTag.getIsOpen());
                                circleTagService.update(t);
                            }
                        }
                    } else {
                        for (CircleTag circleTag : circleInput.getCircleTags()) {
                            if (circleTag.getTagName().equals("其他")) {
                                circleDb.setNoTypeIsOpen(null);
                            } else {
                                CircleTag t = circleTagService.get(circleTag.getId());
                                t.setIsOpen(null);
                                circleTagService.update(t);
                            }
                        }
                    }
                }
                circleService.update(circleDb);
            } else {
                circleInput.setCreateBy(memberId);
                Circle circle = new Circle();
                MyBeanUtils.copyBeanNotNull2Bean(circleInput, circle);// 将编辑表单中的非\NULL值覆盖数据库记录中的值
                circleId = circleBizService.createCircleBiz(circle, memberId);
            }

            circleBizNewService.uploadQrCode(memberId, circleId);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("圈子保存异常", e);
            return AjaxResult.error("圈子保存异常");
        }
    }

    /**
     * 删除圈子
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "dissolveCircle")
    public AjaxResult dissolveCircle(@ControlParam(table = "circle", column = "create_by") String id) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Map<String, Object> searchMap = new HashMap<String, Object>();
            searchMap.put("circleId", id);
            List<WithTage> list = circleMemberBizService.withTageList(searchMap, null);
            if (list.size() == 0) {
                circleBizService.dissolveCircle(id);
                return new AjaxResult(true);
            } else {
                return new AjaxResult(false, "项目下已有会员，不能删除");
            }
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
        }
        return new AjaxResult(false);
    }

    /**
     * 生成相册
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "createPhotos")
    public AjaxResult createPhotosProject(String id) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Circle circle = circleService.get(id);
            PhotoProject photoProject = new PhotoProject();
            photoProject.setMemberId(circle.getCreateBy());
            photoProject.setCircleId(circle.getId());
            photoProject.setName(circle.getName());
            photoProject.setOperatePermission(1);
            if (circle.getMemo() != null) {
                photoProject.setIntroduction(circle.getMemo());
            }
            if (circle.getLogo() != null) {
                photoProject.setPic(circle.getLogo());
            }
            List<PhotoProject> photosList = photoProjectService.list(photoProject);
            if (photosList.size() == 0) {
                photoProjectService.insert(photoProject);
                // 初始化系统标签
                albumBizService.initTags(photoProject.getId());
            } else {
                PhotoProject oldPhotoProject = photosList.get(0);
                oldPhotoProject.setName(circle.getName());
                oldPhotoProject.setPic(circle.getLogo());
                if (circle.getMemo() != null) {
                    oldPhotoProject.setIntroduction(circle.getMemo());
                }
                photoProjectService.update(oldPhotoProject);
            }
            try {
                WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
                XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
                qrCodeRequest.setPage("pages/photo/index");
                qrCodeRequest.setScene(photoProject.getId());
                String filePath = fileBizService.getUploadCIPath(circle.getCreateBy(), "photo");
                fileBizService.uploadCloudOut(photoProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
            } catch (Exception e) {
                logger.error("生成小程序码异常", e);
            }
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
        }
        return AjaxResult.success();
    }

    /**
     * 行知公社圈子数据迁移到子账号下
     *
     * @author yifeng
     * @date 10:38 2019/11/12
     **/
    @ResponseBody
    @RequestMapping(value = "xzgsDataMigration")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult xzgsDataMigration() {
        try {
            String memberId = memberGroupBizService.getXzgsMemberId();
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_JX.getValue(), memberId, XzgsAccountEnum.XZGS_JX.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_QL.getValue(), memberId, XzgsAccountEnum.XZGS_QL.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_YJ.getValue(), memberId, XzgsAccountEnum.XZGS_YJ.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_ZX.getValue(), memberId, XzgsAccountEnum.XZGS_ZX.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_HP.getValue(), memberId, XzgsAccountEnum.XZGS_HP.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_ZY.getValue(), memberId, XzgsAccountEnum.XZGS_ZY.getKey());
            circleBizNewService.xzgsCircleDataMigration(XzgsAccountEnum.XZGS_KP.getValue(), memberId, XzgsAccountEnum.XZGS_KP.getKey());
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("圈子数据迁移异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("圈子数据迁移异常");
        }
    }
}
